//
//  StudentFMDNManager.m
//  FMDBDemo
//
//  Created by 智捷电商APPLE01 on 17/6/6.
//  Copyright © 2017年 智捷电商APPLE01. All rights reserved.
//

#import "StudentFMDNManager.h"
#import "Student.h"

#define STUDENT_TABLE @"STUDENT_TABLE.sqlite"

@implementation StudentFMDNManager

static FMDatabase *_fmdb;

/**
 使用FMDB要导入 libsqlite3.0.tbd
 */
+ (void)initialize {

    //拼接路径
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:STUDENT_TABLE];
    
    //初始化FMDB
    _fmdb = [FMDatabase databaseWithPath:filePath];
    
    //打开数据库
    [_fmdb open];

    //创建学生表
    BOOL isSucc = [_fmdb executeUpdate:@"create table if not exists t_STUDENT_TABLE(id integer primary key, imgURL text, name text, Phone text, times text);"];
    NSLog(@"%d", isSucc);
}

//添加
+ (BOOL)addStudent:(Student *)student {

    NSString *addSql = [NSString stringWithFormat:@"insert into t_STUDENT_TABLE(imgURL, name, Phone, times) values ('%@','%@','%@','%@');", student.imgURL, student.name, student.Phone, student.times];
    
    BOOL isSuccess = [_fmdb executeUpdate:addSql];
    
    return isSuccess;
}

//查询
+ (NSArray <Student *> *)queryStudent:(NSString *)querySql {
    
    if (querySql == nil) {
        querySql = @"select * from t_STUDENT_TABLE;";
    }
    
    NSMutableArray <Student *> *students = [NSMutableArray array];
    FMResultSet *set = [_fmdb executeQuery:querySql];

    while ([set next]) {
        
        NSString *name = [set stringForColumn:@"name"];
        NSString *imgURL = [set stringForColumn:@"imgURL"];
        NSString *Phone = [set stringForColumn:@"Phone"];
        NSString *times = [set stringForColumn:@"times"];

        Student *stu = [Student studentWith:imgURL name:name Phone:Phone Times:times];
        [students addObject:stu];
    }
    return students;
}

+ (BOOL)deleteStudent:(NSString *)deleteSql {
    
    if (deleteSql == nil) {
        deleteSql = @"delete from t_STUDENT_TABLE";
    }
    
    BOOL isSuccess = [_fmdb executeUpdate:deleteSql];
    
    return isSuccess;
    
}

+ (BOOL)updateStudent:(NSString *)updateSql {
    
    if (updateSql == nil) {
        return NO;
    }
    
    BOOL isSuccess = [_fmdb executeUpdate:updateSql];
    
    return isSuccess;
}


@end
